package com.lx.wx.restful.wechat;

import java.io.IOException;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lx.pc.domain.vo.user.UserVo;
import com.lx.pc.domain.vo.wcategory.WCategoryVo;
import com.lx.pc.domain.vo.worder.WOrderVo;
import com.lx.pc.domain.vo.wordercategory.WOrderCategoryVo;
import com.lx.pc.domain.vo.wx.WeixinVo;
import com.lx.pc.service.user.IUserService;
import com.lx.pc.service.wcategory.IWCategoryService;
import com.lx.pc.service.worder.IWOrderService;
import com.lx.pc.service.worderCategory.IWOrderCategoryService;
import com.lx.pc.service.wx.IWeixinService;
import com.lx.pc.utils.DateUtil;
import com.lx.pc.utils.OmsPage;
import com.lx.wx.restful.utils.AjaxResult;
import com.lx.wx.restful.utils.WeiXinUtils;

/**
 * 回收员订单列表
 * @author houzhong
 */
@Controller
@RequestMapping("/wx")
public class ReceiptController{

	/**
	 * 微信获取token
	 */
	@Resource(name = "weixinService")
	private IWeixinService weixinService;
	
	/**
	 * 用户
	 */
	@Resource(name = "userService")
	private IUserService userService;

	/**
	 * 用户订单
	 */
	@Resource(name = "wOrderService")
	private IWOrderService wOrderService;
	
	/**
	 * 用户多个分类多个重量
	 */
	@Resource(name = "wOrderCategoryService")
	private IWOrderCategoryService wOrderCategoryService;
	
	/**
	 * 分类
	 */
	@Resource(name = "wCategoryService")
	private IWCategoryService wCategoryService;
	
	@RequestMapping("/toReceiptOrderList")
	public ModelAndView toReceiptOrderList(HttpServletRequest request,UserVo v) {
		ModelAndView mv = new ModelAndView("/wx/seller/home");

		String code = request.getParameter("code");
		System.out.println("order:code--------" + code);
		//获取公众号信息
		JSONObject jsonObject = WeiXinUtils.getUserInfo(code);
		//获取用户信息
		//UserVo userVo = getOpenId(jsonObject);
		UserVo userVo = userService.findByUsername(v);
		if (userVo.getNickName() == null) {
			//获取微信token
			WeixinVo weixinVo = weixinService.findByWeixin();
			//获取公众号信息
			String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+weixinVo.getAccessToken()+"&openid="+userVo.getWxOpenId()+"&lang=zh_CN";
			JSONObject jsonObject1 = WeiXinUtils.httpRequest(url, "GET", new JSONObject());
			//用户昵称
			String nickName = jsonObject1.getString("nickname");
			//获取用户默认头像
			String headimgurl = jsonObject1.getString("headimgurl");
			userVo.setUserImg(headimgurl);
			userVo.setNickName(nickName);
			//获取用户头像修改
			userService.updateUser(userVo);
		}

		WOrderVo orderVo = new WOrderVo();
		orderVo.setReceiptId(userVo.getbId());
		Integer countNum = wOrderService.findByReceiptCount(orderVo);
		Float totalPrice = 0f;
		if (countNum != 0) {
			WOrderCategoryVo orderCategoryVo = new WOrderCategoryVo();
			orderCategoryVo.setReceiptId(userVo.getbId());
			totalPrice = wOrderCategoryService.findByTotalPriceCount(orderCategoryVo);
		}
		mv.addObject("userVo",userVo);
		//今日接单总数
		mv.addObject("countNum",countNum);
		//今日总价格
		mv.addObject("totalPrice",totalPrice);
		return mv;
	}
	
	/**
	 * 修改状态跳转到订单列表
	 * @param v
	 * @return
	 */
	@RequestMapping("/toReceiptList")
	public ModelAndView toReceiptList(UserVo v) {
		ModelAndView mv = new ModelAndView("/wx/seller/home");
		UserVo userVo = userService.findByUsername(v);
		
		WOrderVo orderVo = new WOrderVo();
		orderVo.setReceiptId(userVo.getbId());
		Integer countNum = wOrderService.findByReceiptCount(orderVo);
		Float totalPrice = 0f;
		if (countNum != 0) {
			WOrderCategoryVo orderCategoryVo = new WOrderCategoryVo();
			orderCategoryVo.setReceiptId(userVo.getbId());
			totalPrice = wOrderCategoryService.findByTotalPriceCount(orderCategoryVo);
		}
		mv.addObject("userVo",userVo);
		//今日接单总数
		mv.addObject("countNum",countNum);
		//今日总价格
		mv.addObject("totalPrice",totalPrice);
		return mv;
	}
	
	
	/**
	 * 获取当前商家的订单
	 * @param v
	 * @param page
	 * @param size
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/serchReceiptOrderList")
    @ResponseBody
    public  String serchReceiptOrderList(WOrderVo v,Integer page,Integer size) throws IOException {
        Map<String,Object> result = new HashMap<String, Object>();
        
        OmsPage<WOrderVo> pages = wOrderService.findByWOrder(v, page, size);
        if (pages.getResult().size()>0) {
        	//查询当前用户订单信息
        	for (WOrderVo orderVo : pages.getResult()) {
        		WOrderCategoryVo orderCategoryVo = new WOrderCategoryVo();
        		orderCategoryVo.setOrderNumber(orderVo.getOrderNumber());
        		orderCategoryVo.setReceiptId(orderVo.getReceiptId());
        		//查询总价
        		WOrderCategoryVo vo = wOrderCategoryService.findBySumPrice(orderCategoryVo);
				if (vo != null) {
					//总价
					orderVo.setCountPrice(vo.getPrice());	
				}
        	}
        }
        result.put("wOrderVo", pages.getResult());
        return JSON.toJSONString(result);
	}
	
	/**
	 * 修改订单状态
	 */
	@RequestMapping("/updateOrderStatus")
    @ResponseBody
    public  AjaxResult<String> updateOrderStatus(WOrderVo v) throws IOException {
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		WOrderVo orderVo = wOrderService.find(new BigInteger(v.getbId()));
		orderVo.setStatus(v.getStatus());
		String flag = wOrderService.updateStatus(orderVo);
		ajaxResult.setMsg(flag);
		return ajaxResult;
	}
	
	/**
	 * 过磅定价
	 */
	@RequestMapping("/toPriced")
	public ModelAndView toPriced(WOrderVo v) {
		ModelAndView mv = new ModelAndView("/wx/seller/priced");
		WOrderVo orderVo = wOrderService.findByOrderNum(v);
		WCategoryVo categoryVo = new WCategoryVo();
		List<WCategoryVo> listCategory = wCategoryService.findByWCategory(categoryVo);
		
		mv.addObject("listCategory",listCategory);
		mv.addObject("orderVo",orderVo);
		return mv;
	}
	
	/**
	 * 更新订单
	 * @param v
	 * @param categoryStr
	 * @param actualWeightStr
	 * @param priceStr
	 * @return
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping(value = "/toUpdateOrder.do")
	public AjaxResult<String> toUpdateOrder(WOrderVo v,
			@RequestParam(value = "categoryStr[]")String[] categoryStr,
			@RequestParam(value = "actualWeightStr[]")String[] actualWeightStr,
			@RequestParam(value = "priceStr[]")String[] priceStr) throws ParseException{
		
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		
		WOrderVo orderVo = wOrderService.find(v.getId());
		orderVo.setStatus(v.getStatus());
		wOrderService.updateStatus(orderVo);
		
		if (categoryStr != null) {
			//分类
			for (int i = 0 ;i<categoryStr.length; i++) {
				WOrderCategoryVo orderCategoryVo = new WOrderCategoryVo();
				orderCategoryVo.setwCategoryId(categoryStr[i]);
				orderCategoryVo.setOrderNumber(orderVo.getOrderNumber());
				List<WOrderCategoryVo>  categoryVos = wOrderCategoryService.findByWOrderCategory(orderCategoryVo);
				if (categoryVos.size()>0) {
					for (WOrderCategoryVo vo : categoryVos) {
						//确认重量
						vo.setActualWeight(actualWeightStr[i]);
						//价格
						vo.setPrice(Float.valueOf(priceStr[i]));
						//更新时间
						vo.setModifyTime(DateUtil.dateFormat());
						wOrderCategoryService.updateOrderCategory(vo);
					}
				}else {
					//确认重量
					orderCategoryVo.setActualWeight(actualWeightStr[i]);
					//价格
					orderCategoryVo.setPrice(Float.valueOf(priceStr[i]));
					//分类
					orderCategoryVo.setwCategoryId(categoryStr[i]);
					//用户重量范围
					orderCategoryVo.setWeight(v.getWeight());
					wOrderCategoryService.save(orderCategoryVo);
				}
			}
		}
		ajaxResult.setMsg("1");
		ajaxResult.setResult(orderVo.getOrderNumber());
		return ajaxResult;
	}
	
	/**
	 * 回收员个人资料
	 * @param v
	 * @return
	 */
	@RequestMapping("/toUser.do")
	public ModelAndView toUser(UserVo v) {
		ModelAndView mv = new ModelAndView("/wx/seller/mine");
		UserVo userVo = userService.findByUsername(v);
		
		mv.addObject("userVo",userVo);
		return mv;
	}
	
	/**
	 * 商家修改基础信息
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toUpdateUser.do")
	public AjaxResult<String> toUpdateUser(UserVo v){
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		UserVo user = new UserVo();
		user.setId(v.getId());
		user = userService.findByUsername(user);
		user.setId(new BigInteger(user.getbId()));
		user.setProvince("江苏省");
		user.setCity(v.getCity().replaceAll(" ", ""));
		user.setArea(v.getArea().replaceAll(" ", ""));
		user.setAddress(v.getAddress());
		user.setContacts(v.getContacts());
		user.setTelephone(v.getTelephone());
		String id = userService.updateUser(user);
		ajaxResult.setMsg(id);
		return ajaxResult;
	}
	
	/**
	 * 进入确定支付方式页面
	 * @param v
	 * @return
	 */
	@RequestMapping("/toPayment.do")
	public ModelAndView toPayment(WOrderVo v,Float total) {
		ModelAndView mv = new ModelAndView("/wx/seller/payment");

		WOrderVo orderVo = wOrderService.find(v.getId());
		//进行中
		orderVo.setStatus(1);
		//未支付
		orderVo.setPaymentStatus(2);
		//更新
		wOrderService.updateStatus(orderVo);
		
		mv.addObject("orderVo",orderVo);
		mv.addObject("total",total);
		return mv;
	}
	
	/**
	 * 修改订单状态
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toUpdateStatus.do")
	public AjaxResult<String> toUpdateStatus(WOrderVo v){
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		WOrderVo orderVo = wOrderService.find(v.getId());
		orderVo.setStatus(v.getStatus());
		orderVo.setPaymentType(v.getPaymentType());
		orderVo.setPaymentStatus(v.getPaymentStatus());
		
		wOrderService.updateStatus(orderVo);
		ajaxResult.setMsg("1");
		return ajaxResult;
	}
	
	/**
	 * 验证openid 是否存在，不存在新增
	 * @param jsonObject
	 * @return
	 */
	public UserVo getOpenId(JSONObject jsonObject) {
		//获取openid
		String openId = jsonObject.getString("openid");
		System.out.println("openid-------" + openId);
		UserVo user = new UserVo();
		user.setWxOpenId(openId);
		user.setWxType(3);
		user = userService.findByUsername(user);
		if (user == null ) {
			user = new UserVo();
			user.setWxOpenId(openId);
			user.setWxType(3);
			user.setStatus(1);
			user.setAuditStatus(3);
			userService.save(user);
		}
		return user;
	}
}
